package net.caixiaomi.info.shopkeeper;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;

import net.caixiaomi.info.R;
import net.caixiaomi.info.WebViewActivity;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.shopkeeper.adapter.ShopOrderAdapter;
import net.caixiaomi.info.shopkeeper.entity.MediaTokenEntity;
import net.caixiaomi.info.shopkeeper.entity.ShopDetailMainEntity;
import net.caixiaomi.info.shopkeeper.entity.ShopOrderEntity;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.info.widgets.DefLoading;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * Created by mac on 2018/11/13.
 */

public class ShopKeeperActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener,View.OnClickListener{

    private boolean mIsLogin=false;

    private static final int CODE_CAMERA_REQUEST = 1000;
    private static final int CODE_RESULT_REQUEST = 1002;

    public static final int LOGIN_CODE=1001;

    private Uri mImageUri;
    private Uri mOutUri;

    @BindView(R.id.shop_orderlist_btn)
    RelativeLayout mOrderBtn;

    @BindView(R.id.shop_login_btn)
    RelativeLayout mLoginBtn;

    @BindView(R.id.shop_getorder_btn)
    RelativeLayout mSetOrderBtn;

    @BindView(R.id.shop_login_tv)
    TextView mLoginTv;

    @BindView(R.id.shop_order_list_tv)
    TextView shopOrderTv;

    @BindView(R.id.shop_no_login_tv)
    TextView noLoginTv;
    @BindView(R.id.shop_no_order_tv)
    TextView noOrderTv;
    @BindView(R.id.shop_order_list)
    LinearLayout shopOrderListLayout;

    ShopPhotoDialog dialog;
    @BindView(android.R.id.list)
    RecyclerView mListView;

    @BindView(R.id.progress)
    CircularProgressBar mProgress;

    @OnClick(R.id.shop_tip)
    void tip(){
        Intent intent = new Intent(this, WebViewActivity.class);
        intent.putExtra("url", "http://t1.caixiaomi.net:9806/description");
        startActivity(intent);
    }

    private ShopOrderAdapter mAdapter;

    private List<ShopOrderEntity> mList;

    private boolean isShowing=false;

    private int mRequestType=0; //0自动刷新，1按钮手动刷新

    @OnClick(R.id.shop_getorder_btn)
    void toGetOrder(){
        initData(1);
    }

    @OnClick(R.id.shop_login_btn)
    void toLogin(){
        if(!mIsLogin) {
            Intent intent = new Intent(this, ShopLoginActivity.class);
            startActivityForResult(intent, LOGIN_CODE);
        }else{
            logout();
        }
    }

    @OnClick(R.id.shop_orderlist_btn)
    void setOrderBtn(){
        Intent intent = new Intent(this, ShopOrderHistoryActivity.class);
        startActivityForResult(intent, LOGIN_CODE);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        CommonApp.mScreenWidth=metrics.widthPixels;
        CommonApp.mScreenHeight=metrics.heightPixels;
        mList=new ArrayList<>();
        initView();
        initData(0);
        mToolbar.setNavigationIcon(null);


    }

    private void initView(){
        setLoginStatus(mIsLogin);
        mListView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ShopOrderAdapter(null);
        mAdapter.setOnItemClickListener(this);
        mListView.setAdapter(mAdapter);
    }

    private void logout(){
        JSONObject params = new JSONObject();
        params.put("str", "");
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel> logoutS = requestService.logOutXN(params);
        logoutS.enqueue(new ResponseCallback<BaseCallModel>() {
            @Override
            public void onSuccess(BaseCallModel data) {
                mIsLogin=false;
                setLoginStatus(mIsLogin);
            }

            @Override
            public void onFail(ResponseError error) {

            }

            @Override
            public void onError() {

            }
        });
    }

    /**
     * type:0自动刷新，1按钮手动刷新
     * @param type
     */
    private void initData(int type){
        mProgress.setVisibility(View.VISIBLE);
        JSONObject params = new JSONObject();
        params.put("type", type);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<List<ShopOrderEntity>>> baseCallModelCall = requestService.queryXN(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel<List<ShopOrderEntity>>>() {
            @Override
            public void onSuccess(BaseCallModel<List<ShopOrderEntity>> data) {
                mProgress.setVisibility(View.GONE);
                mIsLogin=true;
                setLoginStatus(mIsLogin);
                List<ShopOrderEntity>list=data.data;
                mList.clear();
                mList.addAll(list);
                if(list!=null&&list.size()>0){
                    noOrderTv.setVisibility(View.GONE);
                    shopOrderListLayout.setVisibility(View.VISIBLE);
                    mAdapter.setNewData(mList);
                    mAdapter.notifyDataSetChanged();
                }else{
                    noOrderTv.setVisibility(View.VISIBLE);
                    shopOrderListLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                if(error!=null) {
                    ToastUtil.s(error.getMessage());
                }
                if(error.getCode()==600){
                    mIsLogin=false;
                    setLoginStatus(mIsLogin);
                }else{
                    mIsLogin=true;
                    setLoginStatus(mIsLogin);
                    if(error.getCode()==303016){
                        mList.clear();
                        mAdapter.setNewData(mList);
                        mAdapter.notifyDataSetChanged();
                        noOrderTv.setVisibility(View.VISIBLE);
                        shopOrderListLayout.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onError() {
                ToastUtil.s("网络异常");
                mProgress.setVisibility(View.GONE);
            }
        });

    }

    @Override
    protected int layout() {
        return R.layout.shop_keeper_layout;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == CODE_CAMERA_REQUEST) {
                    dialog.setData(data);
                }
                }else if(requestCode==ShopKeeperActivity.LOGIN_CODE){
                    mIsLogin=true;
                    initData(0);
                }
            else {
                super.onActivityResult(requestCode, resultCode, data);

            }}catch (Exception e) {
                e.printStackTrace();
            }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if(isShowing){
            return;
        }
        if(!mList.get(position).getStatus().equals("0")){
            return;
        }
        isShowing=true;
        JSONObject params = new JSONObject();
        params.put("mobile", "");
        params.put("orderSn", mList.get(position).getOrderSn());
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<ShopDetailMainEntity>> call = requestService.detailXN(params);
        mProgress.setVisibility(View.VISIBLE);
        call.enqueue(new ResponseCallback<BaseCallModel<ShopDetailMainEntity>>() {
            @Override
            public void onSuccess(BaseCallModel<ShopDetailMainEntity> data) {
                ShopDetailMainEntity entity=data.data;
                MediaTokenEntity token=entity.getMediaToken();
                PhotoImpl.accessKeyId=token.getAccKeyId();
                PhotoImpl.accessKeySecret=token.getAccKeySecret();
                PhotoImpl.endpoint=token.getUrl();
                PhotoImpl.testBucket=token.getBucketName();
                PhotoImpl.uploadObject=token.getFileName();
                mProgress.setVisibility(View.GONE);
                dialog=new ShopPhotoDialog(ShopKeeperActivity.this, new ShopPhotoDialog.callBack() {
                    @Override
                    public void setPhoto(Intent intent, int requestCode) {
                        startActivityForResult(intent, CODE_CAMERA_REQUEST);
                    }

                    @Override
                    public void success() {
                        initData(0);
                    }

                    @Override
                    public void failure() {
                        initData(0);
                    }
                });
                dialog.setShopEntity(data.data);
                dialog.show();
                dialog.setCancelable(true);

                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        isShowing=false;
                    }
                });
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onClick(View view) {

    }

    private void setLoginStatus(boolean loginStatus){
        if(loginStatus){
            mLoginTv.setText("退出登录");
            shopOrderTv.setTextColor(getResources().getColor(R.color.orange_primary));
            mLoginTv.setTextColor(getResources().getColor(R.color.orange_primary));
            mLoginBtn.setBackgroundResource(R.drawable.btn_orange_white_corner);
            mOrderBtn.setBackgroundResource(R.drawable.btn_orange_white_corner);
            mSetOrderBtn.setBackgroundResource(R.drawable.btn_orange_corner);
            mOrderBtn.setClickable(true);
            mSetOrderBtn.setClickable(true);
            noLoginTv.setVisibility(View.GONE);
        }else{
            mProgress.setVisibility(View.GONE);
            mLoginTv.setText("登录");
            mLoginTv.setTextColor(getResources().getColor(R.color.white));
            shopOrderTv.setTextColor(getResources().getColor(R.color.white));
            mLoginBtn.setBackgroundResource(R.drawable.btn_orange_corner);
            mOrderBtn.setBackgroundResource(R.drawable.btn_shadow_corner);
            mSetOrderBtn.setBackgroundResource(R.drawable.btn_shadow_corner);
            mOrderBtn.setClickable(false);
            mSetOrderBtn.setClickable(false);
            noLoginTv.setVisibility(View.VISIBLE);
            noOrderTv.setVisibility(View.GONE);
            shopOrderListLayout.setVisibility(View.GONE);
        }
    }
}
